package com.cssw.fyzb.tps.api.res;

import com.cssw.fyzb.tps.service.res.AimRes;
import com.cssw.fyzb.tps.util.CurrentTimeMillisId;
import com.cssw.fyzb.tps.util.MimeType;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Property;
import com.ydn.appserver.annotations.Result;
import com.ydn.appserver.annotations.Type;
import com.ydn.appserver.utils.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Feng Chen
 */
@Function(description = "添加资源", parameters = {
        @Parameter(name = "extension", type = Type.String, description = "文件扩展名（可带可不带点）", required = true),
        @Parameter(name = "content", type = Type.String, description = "资源文件内容的 Base64 编码", required = true),
        @Parameter(name = "type", type = Type.String, description = "资源类型，可选值：image/audio/video/document/ebook", required = true)
}, result = @Result(properties = {
        @Property(name = "url", type = Type.String, description = "资源访问地址")
}))
@Component
public class AddRes implements Action {

    @Autowired
    private AimRes aimRes;

    private static final DateFormat FORMAT = new SimpleDateFormat("yyyy/MM/dd");

    private static final Logger logger = LoggerFactory.getLogger(AddRes.class);

    @Override
    public Response execute(Request request) throws Exception {
        String extension = request.getString("extension");
        String encript = request.getString("content");
        String type = request.getString("type");

        // 保证 extension 以 . 开头
        extension = extension.startsWith(".") ? extension : ("." + extension);

        try {
            String url = aimRes.upload(
                    getKey(extension, type),
                    MimeType.getMimeType(extension),
                    Base64.decode(encript)
            );
            return Response.success().put("url", url);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("上传资源失败");
        }
    }

    // 获取地址

    private String getKey(String extension, String type) {
        return new StringBuilder().append(type)
                .append("/")
                .append(FORMAT.format(new Date()))
                .append("/")
                .append(CurrentTimeMillisId.next()).append(extension)
                .toString()
                ;
    }

}
